import PageComponent from '@components/pageComponent'
import style from './index.module.less'
import { useAppDispatch, useAppSelector } from '@src/redux/hook'
import { useEffect, useMemo, useState } from 'react'
import { Button, Form, Input, Toast } from 'antd-mobile'
import styles from './index.module.less'
import { EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons'
import classNames from 'classnames'
import { awaitWrap, compress } from '@src/assets/js/tool'
import { sendSMSRequest, modifyPasswordRequest } from './ajax'
import { logout, setSendTime } from '@src/redux/reducers/basic'
import { setList } from '@src/redux/reducers/pages'
import uuid from 'uuid'
 
let timer
const { Item, useForm } = Form

function validator (rule, value) {
  if (!value) {
    return Promise.resolve()
  }
  if (value.length < 8) {
    return Promise.reject(new Error('最小长度为8位'))
  }
  let count = 0
  if (/[$-]+/.test(value)) {
    return Promise.reject(new Error('新密码不能包含-和$'))
  }
  if (/[a-z]+/.test(value) && /[A-Z]+/.test(value)) {
    count++
  }
  if (/[~!@#%^&*()_+=*/<>?/\\.,;'"]+/.test(value)) {
    count++
  }
  if (/[0-9]+/.test(value)) {
    count++
  }
  if (count < 2) {
    return Promise.reject(new Error('新密码必须包含大小写字母+数字+特殊符号中的两种以上'))
  }
  return Promise.resolve()
}

function loop (sendTime, setSecond) {
  const n = 60 - Math.floor((Date.now() - sendTime) / 1000)
  if (n >= 0) {
    setSecond(n)
    timer = setTimeout(() => {
      loop(sendTime, setSecond)
    }, 1000)
  }
}

async function sendHandle (mobile, callback) {
  if (!mobile) {
    Toast.show({ content: '手机号不能为空' })
    return undefined
  }
  if (!/^1[3-9]\d{9}$/.test(mobile)) {
    Toast.show({ content: '手机号格式不正确' })
    return undefined
  }
  Toast.show({ content: '发送中', icon: 'loading', duration: 0 })
  const [e] = await awaitWrap(sendSMSRequest(compress(mobile)))
  if (e === null) {
    Toast.clear()
    callback()
  }
}

async function submitHandle (d, dispatch) {
  Toast.show({ content: '提交中', icon: 'loading', duration: 0 })
  const [e] = await awaitWrap(modifyPasswordRequest(d.mobile, d.new_password, d.verification))
  if (e === null) {
    Toast.clear()
    Toast.show({ content: '修改成功', icon: 'success'  })
    dispatch(logout())
    dispatch(setList([{ element: 'login', title: '登录', id: uuid() }]))
  }
}

function Main () {
  const dispatch = useAppDispatch()
  const [formRef] = useForm()
  const [visible, setVisible] = useState(false)
  const userInfo = useAppSelector(state => state.basic.userInfo)
  const mobile = useMemo(() => {
    return userInfo ? userInfo.mobile : ''
  }, [userInfo])
  const info = useMemo(() => {
    return userInfo && userInfo.expire_info ? userInfo.expire_info : ''
  }, [userInfo])
  const [second, setSecond] = useState(0)
    const sendTime = useAppSelector(state => state.basic.sendTime)
    useEffect(() => {
      loop(sendTime, setSecond)
      return () => {
        timer && clearTimeout(timer)
      }
    }, [sendTime])
  useEffect(() => {
    formRef.setFieldsValue({
      mobile
    })
  }, [formRef, mobile])
  return (
    <PageComponent title='修改密码'>
      <div className={style.container}>
        {
          info && (
            <div className={style.notice}>
              <div className={style['notice-inner']}>
                <div className={style['notice-text']}>{info}</div>
              </div>
            </div>
          )
        }
        <Form layout='horizontal' form={formRef} onFinish={d => submitHandle(d, dispatch)}>
          <Item label='手机号' name='mobile'>
            <Input placeholder='请输入' readOnly />
          </Item>
          <Item
            label='新密码'
            name='new_password'
            rules={[{ required: true, message: '密码不能为空'  }, { validator }]}
            extra={
              <div className={styles.eye}>
                {!visible ? (
                  <EyeInvisibleOutline onClick={() => setVisible(true)} />
                ) : (
                  <EyeOutline onClick={() => setVisible(false)} />
                )}
              </div>
            }
          >
            <Input placeholder='请输入' type={visible ? 'text' : 'password'} clearable />
          </Item>
          <Item
            label='验证码'
            name='verification'
            rules={[
              { required: true, message: '验证码不能为空' },
              { validator(rule, value) {
                if (value && !/^\d{4}$/.test(value)) {
                  return Promise.reject(new Error('验证码格式不正确'))
                }
                return Promise.resolve()
              }, }
            ]}
            extra={
              (
                second === 0 ? (
                  <div className={style.send} onClick={() => {
                    const mobile = formRef.getFieldValue('mobile')
                    sendHandle(mobile, () => { dispatch(setSendTime(Date.now())) })
                  }}>
                    <a>获取验证码</a>
                  </div>
                ) : (
                  <div className={classNames(style.send, style.disabled)}><span>{second} s</span></div>
                )
              )
            }
          >
            <Input placeholder='请输入验证码' maxLength={4} clearable />
          </Item>
          <Item>
            <Button color='primary' block type='submit'>提交</Button>
          </Item>
        </Form>
      </div>
    </PageComponent>
  )
}

export default Main
